package ru.smc.hogwarts.servlets.messages;

import java.io.IOException;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.NoResultException;
import javax.persistence.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import ru.smc.hogwarts.classes.EMF;
import ru.smc.hogwarts.model.Message;

public class MessagesInfo extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	private HttpSession session;
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		EntityManagerFactory emf = EMF.getInstance().getEMF();
   	    EntityManager em = emf.createEntityManager();
		session = request.getSession(true);
		Message message = null;
		int mid = 0;
		try {
			mid = Integer.parseInt(request.getParameter("id"));
		} catch (NumberFormatException e) {}
		
		session.setAttribute("servletName", getServletName());
		
   		Query query = em.createQuery("select p from Message p where ((p.sender.id=?1 and p.deleteteds=false) or (p.recipient.id =?1 and p.deletetedr=false)) and p.id =?2");
   		int id=(Integer)session.getAttribute("userID");
   		query.setParameter(1, id);
   		query.setParameter(2, mid);
    	try{
       		message = (Message)query.getSingleResult();
       		em.getTransaction().begin();
        	if (message.getRecipient().getId()==id){
        		message.setReaded(true);
        	}
        	
        	em.persist(message);
    		em.getTransaction().commit();
    		request.setAttribute("message", message);
    		em.close();
    		
    		request.getRequestDispatcher("/pages/messages/messageInfo.jsp").forward(request, response);
        }
    	catch (NoResultException e) {
    		//ERROR
    		response.sendRedirect(request.getContextPath() + "/messages");
    	}
    	
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doGet(request, response);
	}
}